package klochkov.snake.model;

import java.awt.Point;
import java.util.Random;

import klochkov.snake.common.*;

/**
 * Represent a frog.A frog can jump and may be eaten by the snake.
 * @author Dmitry_Klochkov
 *
 */
public class Frog extends Entity {
	private final Game game;
	private final EntityCell cell;
	
	public Frog(Game game){
		super(game);
		this.game = game;
		this.cell = new EntityCell(this, CellType.FROG);
	}
	
	public EntityCell getCell() {
		return cell;
	}

	@Override
	public void move() {
		
		Random random = new Random();
		try {
			Thread.sleep(1000*random.nextInt(5)+1);
		} catch (InterruptedException e) {}
		
		Point nextCell = new Point();
		Direction dir = Direction.RIGTH;
		int curX = cell.getX();
		int curY = cell.getY();
		int nextX;
		int nextY;
		boolean curLock;
		boolean nextLock;
		while (true) {
			switch (random.nextInt(4)) {
			case 0:
				dir=Direction.UP;
				break;
			case 1:
				dir=Direction.RIGTH;
				break;
			case 2:
				dir=Direction.DOWN;
				break;
			case 3:
				dir=Direction.LEFT;
				break;
			default:
				break;
			}
			nextCell=game.calcNextCell(curX, curY,dir);
			nextX = nextCell.x;
			nextY= nextCell.y;
			
			if(game.isEmpty(nextX, nextY)){
				curLock = game.tryLock(curX,curY);
				nextLock = game.tryLock(nextX, nextY);
				
				if(curLock&&nextLock&&game.isEmpty(nextX, nextY))
				{
					cell.setX(nextX);
					cell.setY(nextY);
					game.getGameField()[curY][curX].clear();
					game.getGameField()[nextY][nextX].setEntityCell(cell);
					game.unlock(curX, curY);
					game.unlock(nextX,nextY);
					return;
				}else{
					if(curLock){
						game.unlock(curX, curY);
					}
					if(nextLock){
						game.unlock(nextX, nextY);
					}
				}
			}
		}
		
	}
	
	
}
